package com.lzk.controller.back;

import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.core.Path;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.upload.UploadFile;
import com.lzk.model.ZcUser;
import com.lzk.service.UserService;
import com.lzk.service.impl.UserServiceImpl;
import com.lzk.util.Util;
import com.lzk.validator.UserValidator;

@Path("/back/user")
public class UserController extends BackBaseController{
	UserService us = new UserServiceImpl();
	public void checkUserName() {
		String userName = getPara("userName");
		boolean flag = us.checkUserName(userName);
		if(flag) {
			renderJson(Ret.fail("用户名重复！"));
		}else {
			renderJson(Ret.ok("用户名不重复！"));
		}
	}
	
	@Before(UserValidator.class)
	public void add() {
		//二进制流文件上传
		UploadFile uf = getFile();
		//文件移动
		//默认在哪里？
		String fileName = Util.moveFileToDireTory(uf.getFile(), PropKit.get("userHeadImg"));
		ZcUser user = getBean(ZcUser.class,"");
		
		if(fileName==null) {
			renderJson(Ret.fail("文件上传失败！"));
		}else {
			user.setHeadImg(fileName);
		}
		boolean flag = us.insertUser(user);
		if (flag) {
			renderJson(Ret.ok("添加成功！"));
		}else {
			renderJson(Ret.fail("添加失败！"));
		}
		
	}
	//必须验证getFile() 文件上传二进制文件流
	public void edit() {
		//二进制流文件上传
		UploadFile uf = getFile();
		ZcUser user = getBean(ZcUser.class,"");
		//不改头像
		if (uf==null) {
			user.setHeadImg(null);
		}else {
			String fileName = Util.moveFileToDireTory(uf.getFile(), PropKit.get("userHeadImg"));
			if(fileName==null) {
				renderJson(Ret.fail("文件上传失败！"));
				return;
			}else {
				user.setHeadImg(fileName);
			}
		}
		boolean isChange=getParaToBoolean("isChange");
		boolean flag = us.editUser(user,isChange);
		if (flag) {
			renderJson(Ret.ok("编辑成功！"));
		}else {
			renderJson(Ret.fail("编辑失败！"));
		}
	}
	public void del() {
		int id = getParaToInt("id");
		boolean flag=us.deleteUserById(id);
		if(flag) {
			renderJson(Ret.ok("删除成功！"));
		}else {
			renderJson(Ret.fail("删除失败！请重试！"));
		}
	}
	public void list() {
		int limit = getParaToInt("limit");//一页几个
		int page = getParaToInt("page");//第几页
		String userName = getPara("userName");
		String userStatus = getPara("userStatus");
		
		List<ZcUser> list = us.getUserListByConection(page,limit,userName,userStatus);
		long count = us.getUserContByConection(userName,userStatus);
		
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("code", 0);
		jsonObject.put("msg", "");
		jsonObject.put("data", list);
		jsonObject.put("count", count);
		renderJson(jsonObject);
	}
	public void show() {
		int id=getParaToInt("id");
		ZcUser user = us.getUserById(id);
		if(user==null) {
			renderJson(Ret.fail("当前用户不存在，或出现异常！"));
		}else {
			renderJson(Ret.ok("data",user));
		}
	}
}
